import Vue from "vue";
import VueX from "vuex";
import createPersistedState from "vuex-persistedstate";
import axios from "@/utils/axios";

Vue.use(VueX);

const store = new VueX.Store({
  plugins: [
    createPersistedState({
      storage: window.sessionStorage,
    }),
  ],
  state: {
    auditDetail: {},
    loginAdmin: {},
    isLogin: false,
    permissions: [],
  },
  getters: {
    getAuditDetail: (state) => state.auditDetail,
    getLoginAdmin: (state) => state.loginAdmin,
    getIsLogin: (state) => state.isLogin,
    getPermissions: (state) => state.permissions,
  },
  mutations: {
    setAuditDetail(state, payload) {
      state.auditDetail = payload;
    },
    setLoginAdmin(state, payload) {
      state.loginAdmin = payload;
    },
    setIsLogin(state, payload) {
      state.isLogin = payload;
    },
    setPermissions(state, payload) {
      state.permissions = payload;
    },
  },
  actions: {
    setAuditDetail({ commit }, payload) {
      commit("setAuditDetail", payload);
    },
    setLoginAdmin({ commit }, payload) {
      commit("setLoginAdmin", payload);
    },
    setIsLogin({ commit }, payload) {
      commit("setIsLogin", payload);
    },
    fetchPermissions({ commit }, roleId) {
      // 假设你使用 axios 进行 HTTP 请求
      return axios
        .get(`/roles/${roleId}/permissions`)
        .then((response) => {
          const permissions = response.data.data.map(
            (permission) => permission.name
          );
          commit("setPermissions", permissions);
        });
    },
  },
});

export default store;
